package com.xiaoai.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuqingxin 2021/8/30 9:50 上午
 */
public class RedisPoolReHot {
    public static final Logger logger = LoggerFactory.getLogger(RedisPoolReHot.class);

    public static void main(String[] args) throws Exception {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(20);
        jedisPoolConfig.setMaxIdle(10);
        jedisPoolConfig.setMinIdle(5);

        String ip = "127.0.0.1";
        int port = 6379;
        int timeout = 0;
        JedisPool pool = new JedisPool(jedisPoolConfig, ip, port, timeout);

        List<Jedis> minIdleJedisList = new ArrayList<>(jedisPoolConfig.getMinIdle());

        for (int i = 0; i < jedisPoolConfig.getMinIdle(); i++) {
            Jedis jedis = null;
            try {
                jedis = pool.getResource();
                minIdleJedisList.add(jedis);
                jedis.ping();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                //注意，这里不能马上close将连接还回连接池，否则最后连接池里只会建立1个连接。。
                //jedis.close();
            }
        }
        //统一将预热的连接还回连接池
        for (int i = 0; i < jedisPoolConfig.getMinIdle(); i++) {
            Jedis jedis = null;
            try {
                jedis = minIdleJedisList.get(i);
                //将连接归还回连接池
                jedis.close();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
            }
        }
    }
}
